const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const formatNumber = (n) => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const encryptPhoneNumber = (phoneNumber) => {
  if (!phoneNumber) return ''
  if (phoneNumber.length === 11) {
    // 通常手机号长度为11位
    return phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  return phoneNumber // 如果不是11位，直接返回原号码
}

// 请求api地址
const apiUrl = 'https://cx.xnvzj.com/' //测试
// 设置锁，默认为开启
var lock = true
// 发起request请求`
function request(url, data, method, header, isLock = false, isIndex = false) {
  if (isLock) {
    if (!lock) {
      return false
    }
  }
  var token = wx.getStorageSync('token') || ''
  var openid = wx.getStorageSync('openid') || ''
  if (data == undefined) {
    data = {
      token: token
    }
  } else {
    data.token = token
  }
  var method = method || 'GET'
  if (!header) {
    header = {
      'access-token': token
    }
    if (method == 'GET' || method == 'get') header['Accept'] = 'application/json'

    if (method == 'POST' || method == 'post') header['content-type'] = 'application/x-www-form-urlencoded'
  }

  header.wxopenid = wx.getStorageSync('openid') || ''
  return new Promise((resolve, reject) => {
    if (isLock) {
      // 上锁
      lock = false
    }
    // 发起请求
    wx.request({
      url: apiUrl + url,
      method: method,
      header: header,
      data: data,
      success: (res) => {
        let errorCode = res.data.code
        if (errorCode == 1) {
          //登录过期
          if (token && openid) {
            //如果token存在则说明用户登录过小程序，则重新获取token实现登录有效期存续
            getToken()
          } else {
            // 判断是否是首页
            if (!isIndex) {
              let msg = res.data.msg
              if (!token) msg = '未登录，即将跳转登录页...'
              wx.showToast(
                {
                  title: msg,
                  icon: 'none',
                  success: function () {
                    // 过期跳转登录页面
                    setTimeout(() => {
                      wx.reLaunch({
                        url: '/pages/gologin/gologin'
                      })
                    }, 1000)
                  }
                },
                1000
              )
            }
          }
        } else if (errorCode == -2) {
          wx.navigateTo({
            url: '/pages/Bindphone/Bindphone'
          })
        } else if (errorCode == -3) {
          wx.navigateTo({
            url: '/pages/Process/process?studentNum=1'
          })
        }
        resolve(res)
      },
      fail: (res) => {
        wx.showToast({
          title: '网络错误',
          icon: 'loading'
        })
        reject(res)
      },
      complete: () => {
        if (isLock) {
          // 解锁
          lock = true
        }
      }
    })
  })
}
// 静默获取token登录
function getToken() {
  const userInfo = wx.getStorageSync('user')
  // 获取code
  wx.login({
    success: (res) => {
      if (res.code) {
        //发起网络请求
        wx.request({
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          url: apiUrl + '/api/login/codeGetOpenid',
          data: {
            code: res.code,
            nickname: userInfo.nickName ? userInfo.nickName : userInfo.nickname,
            avatarUrl: userInfo.avatarUrl ? userInfo.avatarUrl : userInfo.avatar,
            city: userInfo.city,
            country: userInfo.country
          },
          dataType: 'json',
          success: function (response) {
            var res = response.data
            if (res.code == 0) {
              //可以把token和用户信息保存到本地缓存，前后端携带token交互
              wx.setStorageSync('token', res.data.token)
              console.log('旧token过期，重新设置', res.data.token)
            } else {
              console.log(res.msg)
            }
          }
        })
      }
    }
  })
}
// ------------------封装提示框
function showtoast(infos, num, src, type) {
  var msg = infos.msg ? infos.msg : ''
  var icon = infos.icon ? infos.icon : 'none'
  var num = num ? num : 0
  var type = type ? type : 0
  if (src) {
    //跳转弹窗
    let a = setInterval(function () {
      clearInterval(a)
      if (src) {
        if (type == 1) {
          //菜单栏跳转
          wx.switchTab({
            url: src
          })
        } else {
          //普通跳转
          wx.navigateTo({
            url: src
          })
        }
      }
    }, num)
    wx.showToast({
      title: msg,
      icon: icon,
      duration: num,
      mask: true
    })
  } else {
    //普通弹窗
    wx.showToast({
      title: msg,
      icon: icon, //图标，支持"success"、"loading"
      //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
      duration: num, //提示的延迟时间，单位毫秒，默认：1500
      mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
      success: function () {
        setTimeout(function () {}, num)
      }
    })
  }
}
//返回上一页
function navigateBack() {
  var self = this
  var pages = getCurrentPages()
  if (pages.length == 1) {
    if (self.data.circleId && self.data.circleId > 0) {
      wx.redirectTo({
        url: '../../circle/index/index?circleId=' + self.data.circleId + '&circleName=' + (self.data.circleName || '')
      })
    } else {
      wx.switchTab({
        url: '../../home/grouplist/grouplist'
      })
    }
  } else {
    wx.navigateBack({
      changed: true
    }) //返回上一页
  }
}

function onBack() {
  wx.navigateBack()
}

function onGoHome() {
  wx.reLaunch({
    url: '/pages/home/index'
  })
}

function isLogin() {
  const token = wx.getStorageSync('token')
  if (!token) {
    wx.showToast({
      title: '未登录，即将跳转登录页...',
      icon: 'none', //图标，支持"success"、"loading"
      success: function () {
        // 未登录跳转登录页面
        setTimeout(() => {
          wx.reLaunch({
            url: '/pages/gologin/gologin'
          })
        }, 1000)
      }
    })
  } else {
    return true
  }
}
//自定义顶部样式
// function diy_top_content() {
//   var systeminfo = wx.getWindowInfo()
//   //console.log(systeminfo.windowHeight)
//   this.setData({
//     movehight: systeminfo.windowHeight,
//     movehight2: systeminfo.windowHeight - 100
//   })

//   this.setData({
//     menuButtonInfo: wx.getMenuButtonBoundingClientRect()
//   })
//   console.log(this.data.menuButtonInfo)
//   //搜索功能
//   const { top, width, height, right } = this.data.menuButtonInfo
//   wx.getSystemInfo({
//     success: (res) => {
//       const { statusBarHeight } = res
//       const margin = top - statusBarHeight
//       this.setData({
//         navHeight: height + statusBarHeight + margin * 2,
//         searchMarginTop: statusBarHeight + margin, // 状态栏 + 胶囊按钮边距
//         searchHeight: height // 与胶囊按钮同高
//       })
//     }
//   })
// }

// 将图片地址转为base64格式
const Background_base64 = function (path) {
  return 'data:image/jpg;base64,' + wx.getFileSystemManager().readFileSync(path, 'base64')
}
// 防抖函数
function debounce(func, wait) {
  let timeout
  let count = 0
  return function () {
    const args = arguments
    // 计数
    count += 1
    if (count > 3) {
      wx.showToast({
        title: '请勿频繁点击',
        icon: 'none'
      })
      clearTimeout(timeout)
      count = 0
      return
    }
    const context = this
    clearTimeout(timeout)
    timeout = setTimeout(function () {
      func.apply(context, args)
    }, wait)
  }
}
//节流
function throttle(func, wait = 500) {
  let sign = false
  return function () {
    if (sign) return

    sign = true
    setTimeout(() => {
      func.apply(this, arguments)
      sign = false
    }, wait)
  }
}

/*
 * TDesign组件库
 * @author dou   2023-05-19
 */
// 模态框-弹窗
function handlePopup(e) {}

function onVisibleChange(e) {}
//单选按钮组-选择
function onChange(event) {}

//判断字段是否为空
function isFalseValue(val) {
  if (val === undefined || val === null || val === '') return true
  if (JSON.parse(val) === 0) return true

  return false
}

/**
 * 地址解析为结构化对象
 * @param {string} address 地址字符串
 * @returns {{
 *   province: string,
 *   city: string,
 *   area: string,
 *   detail: string
 * }} 地址对象
 */
function parseAddress(address) {
  const deviceInfo = wx.getDeviceInfo()
  //ios和安卓地址返回不一致
  const system = deviceInfo.system

  const reg = /.+?(省|市|自治区|自治州|县|区)/g
  const list = address.match(reg)
  let detail = null

  const municipalities = {
    北京市: '北京市',
    天津市: '天津市',
    上海市: '上海市',
    重庆市: '重庆市'
  }

  const muniKey = Object.keys(municipalities).find((item) => item === list[0])
  if (muniKey && system.indexOf('Android') === -1) {
    list.unshift(municipalities[muniKey])
    detail = address.substring(list[1].length + list[2].length)
  } else {
    detail = address.substring(list[0].length + list[1].length + list[2].length)
  }

  let province = list[0],
    city = list[1],
    area = list[2]

  return {
    province,
    city,
    area,
    detail
  }
}

/**
 * 设置购物车下标
 * @param {*} cartList
 */
function setCartCount(cartList) {
  let allNum = 0
  for (var i = 0; i < cartList.length; i++) {
    if (cartList[i].select === 1 || cartList[i].select === 'success') {
      allNum += parseInt(cartList[i].goods_number)
    }
  }

  console.log('设置购物车下标')
  if (allNum) {
    wx.setTabBarBadge({
      index: 2,
      text: String(allNum)
    })
  } else {
    wx.removeTabBarBadge({
      index: 2
    })
  }
}
module.exports = {
  formatTime,
  apiUrl,
  request,
  showtoast,
  navigateBack,
  // diy_top_content,
  onBack,
  onGoHome,
  isLogin,
  Background_base64,
  debounce,
  throttle,
  isFalseValue,
  parseAddress,
  setCartCount,
  encryptPhoneNumber
}
